package com.pig.common;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author by 李志伟
 * Create Date: 2019/1/7 13:47
 * Description:
 */
@Slf4j
public class MethodUtils {

    /**
     * 生成方法的hashCode
     *
     * @param method
     * @return
     */
    public static String methodEncode(Method method) {
        String className = method.getDeclaringClass().getName();
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();

        List<String> parameterClassNameList = Arrays.stream(parameterTypes).map(aClass -> aClass.getName()).collect(Collectors.toList());

        WrapperRpcRequest wrapperRpcRequest = new WrapperRpcRequest();
        wrapperRpcRequest.setClassName(className);
        wrapperRpcRequest.setMethodName(methodName);
        wrapperRpcRequest.setParameterClassName(parameterClassNameList);

        String methodInfoStr = JsonUtils.objToJsonStr(wrapperRpcRequest);
        log.info("method_info = {}", methodInfoStr);
        String encodeToString = Base64.getEncoder().encodeToString(methodInfoStr.getBytes());
        return encodeToString.replace("=", "");
    }

    public static String argEncode(Object[] args) {
        if (args == null) {
            return "";
        }
        String argsStr = JsonUtils.objToJsonStr(args);
        String encodeToString = Base64.getEncoder().encodeToString(argsStr.getBytes());
        return encodeToString.replace("=", "");
    }

}
